import datetime

# 添加缺失的导入
from flask import Blueprint, jsonify, request, current_app
import jwt
import datetime

from src.models.user_models import db, User, UserWallet, UserVip, Order
from src.routes.auth import token_required

payment_bp = Blueprint('payment', __name__)

# 创建订单
@payment_bp.route('/create-order', methods=['POST'])
@token_required
def create_order(current_user):
    data = request.json
    
    # 验证必要字段
    if not data or not data.get('productType') or not data.get('amount'):
        return jsonify({
            'code': 400,
            'message': '请提供产品类型和金额',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 400
    
    # 生成订单号
    order_no = f"ORD{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:6]}"
    
    # 创建订单
    order = Order(
        order_no=order_no,
        user_id=current_user.id,
        product_type=data.get('productType'),
        product_id=data.get('productId'),
        amount=data.get('amount'),
        status=0,  # 未支付
        create_time=datetime.datetime.now(),
        update_time=datetime.datetime.now()
    )
    
    try:
        db.session.add(order)
        db.session.commit()
        
        # 构建响应数据
        response_data = {
            'orderId': order.id,
            'orderNo': order.order_no,
            'amount': float(order.amount),
            'productType': order.product_type,
            'productId': order.product_id,
            'status': order.status,
            'createTime': order.create_time.strftime('%Y-%m-%d %H:%M:%S')
        }
        
        return jsonify({
            'code': 200,
            'message': '订单创建成功',
            'data': response_data,
            'timestamp': datetime.datetime.now().timestamp()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'订单创建失败: {str(e)}',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 500

# 支付订单（模拟支付）
@payment_bp.route('/pay-order', methods=['POST'])
@token_required
def pay_order(current_user):
    data = request.json
    
    # 验证必要字段
    if not data or not data.get('orderNo') or not data.get('paymentType'):
        return jsonify({
            'code': 400,
            'message': '请提供订单号和支付方式',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 400
    
    # 查询订单
    order = Order.query.filter_by(order_no=data.get('orderNo')).first()
    if not order:
        return jsonify({
            'code': 404,
            'message': '订单不存在',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    # 检查订单状态
    if order.status != 0:
        return jsonify({
            'code': 400,
            'message': '订单状态异常，无法支付',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 400
    
    # 检查订单是否属于当前用户
    if order.user_id != current_user.id:
        return jsonify({
            'code': 403,
            'message': '无权操作此订单',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 403
    
    # 查询用户钱包
    wallet = UserWallet.query.filter_by(user_id=current_user.id).first()
    if not wallet:
        return jsonify({
            'code': 404,
            'message': '用户钱包不存在',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    # 检查余额是否充足
    if float(wallet.balance) < float(order.amount):
        return jsonify({
            'code': 400,
            'message': '余额不足',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 400
    
    try:
        # 更新订单状态
        order.status = 1  # 已支付
        order.payment_type = data.get('paymentType')
        order.payment_time = datetime.datetime.now()
        order.update_time = datetime.datetime.now()
        
        # 更新用户钱包
        wallet.balance = float(wallet.balance) - float(order.amount)
        wallet.total_consume = float(wallet.total_consume) + float(order.amount)
        wallet.update_time = datetime.datetime.now()
        
        # 如果是VIP订单，创建或更新会员信息
        if order.product_type == 'vip':
            # 查询现有会员信息
            vip = UserVip.query.filter_by(user_id=current_user.id).first()
            
            # 计算会员到期时间
            if vip and vip.expire_time > datetime.datetime.now():
                # 已有有效会员，延长有效期
                expire_time = vip.expire_time + datetime.timedelta(days=365)  # 延长一年
                vip.expire_time = expire_time
                vip.status = 1
                vip.update_time = datetime.datetime.now()
            else:
                # 无会员或会员已过期，创建新会员
                start_time = datetime.datetime.now()
                expire_time = start_time + datetime.timedelta(days=365)  # 一年有效期
                
                if vip:
                    # 更新现有会员记录
                    vip.vip_type = 1  # 无限使用
                    vip.start_time = start_time
                    vip.expire_time = expire_time
                    vip.status = 1
                    vip.update_time = datetime.datetime.now()
                else:
                    # 创建新会员记录
                    new_vip = UserVip(
                        user_id=current_user.id,
                        vip_type=1,  # 无限使用
                        start_time=start_time,
                        expire_time=expire_time,
                        status=1,
                        create_time=datetime.datetime.now(),
                        update_time=datetime.datetime.now()
                    )
                    db.session.add(new_vip)
        
        # 如果是内容付费订单，更新相应内容的付费状态
        if order.product_type == 'bazi_detail' and order.product_id:
            from src.models.bazi_models import BaziAnalysis
            bazi_analysis = BaziAnalysis.query.filter_by(bazi_id=order.product_id).first()
            if bazi_analysis:
                bazi_analysis.is_paid = 1
                bazi_analysis.update_time = datetime.datetime.now()
        
        elif order.product_type == 'character_detail' and order.product_id:
            from src.models.character_models import CharacterAnalysis
            character_analysis = CharacterAnalysis.query.filter_by(character_id=order.product_id).first()
            if character_analysis:
                character_analysis.is_paid = 1
                character_analysis.update_time = datetime.datetime.now()
        
        elif order.product_type == 'fengshui_detail' and order.product_id:
            from src.models.fengshui_models import FengshuiAnalysis
            fengshui_analysis = FengshuiAnalysis.query.filter_by(fengshui_id=order.product_id).first()
            if fengshui_analysis:
                fengshui_analysis.is_paid = 1
                fengshui_analysis.update_time = datetime.datetime.now()
        
        db.session.commit()
        
        # 构建响应数据
        response_data = {
            'orderId': order.id,
            'orderNo': order.order_no,
            'amount': float(order.amount),
            'status': order.status,
            'paymentType': order.payment_type,
            'paymentTime': order.payment_time.strftime('%Y-%m-%d %H:%M:%S'),
            'balance': float(wallet.balance)
        }
        
        return jsonify({
            'code': 200,
            'message': '支付成功',
            'data': response_data,
            'timestamp': datetime.datetime.now().timestamp()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'支付失败: {str(e)}',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 500

# 充值钱包（模拟充值）
@payment_bp.route('/recharge', methods=['POST'])
@token_required
def recharge_wallet(current_user):
    data = request.json
    
    # 验证必要字段
    if not data or not data.get('amount') or not data.get('paymentType'):
        return jsonify({
            'code': 400,
            'message': '请提供充值金额和支付方式',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 400
    
    # 查询用户钱包
    wallet = UserWallet.query.filter_by(user_id=current_user.id).first()
    if not wallet:
        return jsonify({
            'code': 404,
            'message': '用户钱包不存在',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    try:
        # 更新钱包余额
        amount = float(data.get('amount'))
        wallet.balance = float(wallet.balance) + amount
        wallet.total_recharge = float(wallet.total_recharge) + amount
        wallet.update_time = datetime.datetime.now()
        
        db.session.commit()
        
        # 构建响应数据
        response_data = {
            'userId': current_user.id,
            'balance': float(wallet.balance),
            'totalRecharge': float(wallet.total_recharge),
            'rechargeAmount': amount,
            'rechargeTime': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        return jsonify({
            'code': 200,
            'message': '充值成功',
            'data': response_data,
            'timestamp': datetime.datetime.now().timestamp()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'充值失败: {str(e)}',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 500

# 获取订单列表
@payment_bp.route('/orders', methods=['GET'])
@token_required
def get_user_orders(current_user):
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    orders = Order.query.filter_by(user_id=current_user.id).order_by(Order.create_time.desc()).paginate(page=page, per_page=per_page)
    
    orders_list = []
    for order in orders.items:
        orders_list.append({
            'orderId': order.id,
            'orderNo': order.order_no,
            'productType': order.product_type,
            'productId': order.product_id,
            'amount': float(order.amount),
            'paymentType': order.payment_type,
            'paymentTime': order.payment_time.strftime('%Y-%m-%d %H:%M:%S') if order.payment_time else None,
            'status': order.status,
            'createTime': order.create_time.strftime('%Y-%m-%d %H:%M:%S')
        })
    
    return jsonify({
        'code': 200,
        'message': '获取成功',
        'data': {
            'orders': orders_list,
            'pagination': {
                'total': orders.total,
                'pages': orders.pages,
                'page': orders.page,
                'per_page': orders.per_page
            }
        },
        'timestamp': datetime.datetime.now().timestamp()
    }), 200

# 获取钱包信息
@payment_bp.route('/wallet', methods=['GET'])
@token_required
def get_wallet_info(current_user):
    wallet = UserWallet.query.filter_by(user_id=current_user.id).first()
    
    if not wallet:
        return jsonify({
            'code': 404,
            'message': '用户钱包不存在',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    # 查询会员信息
    vip = UserVip.query.filter_by(user_id=current_user.id, status=1).first()
    is_vip = False
    vip_expire_time = None
    if vip and vip.expire_time > datetime.datetime.now():
        is_vip = True
        vip_expire_time = vip.expire_time.strftime('%Y-%m-%d %H:%M:%S')
    
    response_data = {
        'userId': current_user.id,
        'balance': float(wallet.balance),
        'totalRecharge': float(wallet.total_recharge),
        'totalConsume': float(wallet.total_consume),
        'status': wallet.status,
        'isVip': is_vip,
        'vipExpireTime': vip_expire_time
    }
    
    return jsonify({
        'code': 200,
        'message': '获取成功',
        'data': response_data,
        'timestamp': datetime.datetime.now().timestamp()
    }), 200
